package com.topgay.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;

import javax.activation.FileDataSource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.topgay.domain.Member;
import com.topgay.service.MemberService;

@Controller
@RequestMapping("/member/")
public class MemberController {

	@Autowired
	private MemberService service;
	
	@Autowired
	private JavaMailSender mailSender;	//메일전송

	@RequestMapping(value = "login.do", method = RequestMethod.GET)
	public String loginForm() {
		return "index/signin";// View Name 리턴
	}

	@RequestMapping(value = "login.do", method = RequestMethod.POST)
	public String login(@RequestParam String id, String password,
			HttpSession session, ModelMap map) throws SQLException {

		Member member = service.getMemberById(id);

		if (member != null) {
			if (password.equals(member.getPassword())) {
				// 로그인 성공
				service.updateLoginCheck(id);
				member = service.getMemberById(id);
				session.setAttribute("login_info", member);
				return "index/main";
			} else {
				// 로그인 실패 : 비번 일치안함
				map.addAttribute("error_message", "비밀번호가 틀렸습니다.");
			}
		} else {
			// ID가 틀린경우, DB에 회원정보값 없음
			map.addAttribute("error_message", "ID정보가 없습니다. 다시 한번 확인 부탁드립니다.");
		}
		return "index/signin";// View Name 리턴
	}// login end

	// 로그아웃
	@RequestMapping(value = "logout.do")
	public String logout(@RequestParam String id, HttpSession session,
			ModelMap map) throws SQLException {
		// 세션을 소멸 -> main.jsp
		Member loginInfo = (Member) session.getAttribute("login_info");
		if (loginInfo != null) {
			// 회원 정보 조회
			service.updateLogoutCheck(loginInfo.getId());
			// 로그아웃 처리
			session.invalidate();
		}
		return "index/main";
	}

	// 가입 폼
	@RequestMapping(value = "join.do", method = RequestMethod.GET)
	public String joinForm() {
		return "member/join_form";
	}

	// 가입 처리
	@RequestMapping(value = "join.do", method = RequestMethod.POST)
	public String joinMember(Member member) throws SQLException {
		service.joinMember(member);

		return "member/join_success";
	}

	// 회원 정보 조회
	@RequestMapping("login/getMemberInfo.do")
	public String getMemberInfo(HttpSession session, ModelMap map) {
		return "member.mypage/modify_info";
	}

	// ID 중복 체크 처리 Controller
	@RequestMapping(value = "idcheck.do", method = RequestMethod.POST)
	protected void idcheck(@RequestParam String id, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			SQLException {

		Member member = service.getMemberById(id);
		// 중복 ID 인지 체크
		boolean flag1;
		if (member != null) {
			flag1 = true;// true : 중복ID(X), false : 사용가능 ID
		} else {
			flag1 = false;
		}
		// 응답처리
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(flag1);
	}

	// 닉네임 중복 체크 처리 Controller
	@RequestMapping(value = "nick_check.do", method = RequestMethod.POST)
	protected void nicknameCheck(@RequestParam String nickname,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {

		Member member = service.getMemberByNickname(nickname);
		// 중복 ID 인지 체크
		boolean flag2;
		if (member != null) {
			flag2 = true;// true : 중복닉네임(X), false : 사용가능 닉네임
		} else {
			flag2 = false;
		}
		// 응답처리
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(flag2);
	}

	// 수정폼
	@RequestMapping(value = "login/modify.do", method = RequestMethod.GET)
	public ModelAndView modifyForm(HttpSession session) {
		Member member = (Member) session.getAttribute("login_info");

		HashMap map = new HashMap();

		String hp[] = member.getHp().split("-");
		map.put("hp1", hp[0]);
		map.put("hp2", hp[1]);
		map.put("hp3", hp[2]);

		String email[] = member.getEmail().split("@");
		map.put("email1", email[0]);
		map.put("email2", email[1]);

		return new ModelAndView("member.mypage/modify_form", map);
	}

	// 수정처리
	@RequestMapping(value = "login/modify.do", method = RequestMethod.POST)
	public String modifyMemberInfo(HttpSession session, Member member,
			ModelMap map) throws Exception {
		Member loginInfo = (Member) session.getAttribute("login_info");
		// 비지니스 로직 - service.modifyMember(수정할 정보)
		System.out.println(member);
		service.modifyMember(member);
		// Session의 회원정보 수정
		member.setJoinDate(loginInfo.getJoinDate());
		session.setAttribute("login_info", member);

		return "member.mypage/modify_info";
	}

	// 탈퇴
	@RequestMapping("login/removeMember.do")
	public String removeMember(HttpSession session, ModelMap map)
			throws Exception {
		// 로그인 확인O
		Member loginInfo = (Member) session.getAttribute("login_info");
		if (loginInfo == null) {
			map.addAttribute("error_message", "로그인 후 탈퇴 가능 합니다.");
			return "member/join_form";
		} else {
			// 회원 정보 삭제 - removeMemberById
			service.removeMemberById(loginInfo.getId());
			// 로그아웃 처리
			session.invalidate();
		}
		return "index/main";
	}

	// 아이디찾기 폼
	@RequestMapping(value = "findId.do", method = RequestMethod.GET)
	public String findForm() {
		return "member/find_id";
	}

	// 아이디 찾기 처리
	@RequestMapping(value = "findId.do", method = RequestMethod.POST)
	public String findMemberById(@RequestParam String name, String hp,
			ModelMap map) throws SQLException {
		Member member = service.findMemberById(name, hp);
		if (member != null) {
			if (name.equals(member.getName())) {
				if (hp.equals(member.getHp())) {
					System.out.println("아이디 찾기 성공");
					System.out.println(member.getName() + "," + member.getHp()
							+ "," + member.getId());
					map.addAttribute("member", member);
					return "member/id_search";
				}
			}
		} else {
			map.addAttribute("error_message", "정보가 잘못되었습니다. 다시 한번 정확히 검색 해주세요.");
		}
		return "member/find_id";
	}

	// 패스워드찾기 폼
	@RequestMapping(value = "findPw.do", method = RequestMethod.GET)
	public String findPwForm(String name, String hp) {
		return "member/find_pw";
	}

	// 패스워드 찾기 처리
	@RequestMapping(value = "findPw.do", method = RequestMethod.POST)
	public String findMemberByPw(@RequestParam String id, String name,
			String hp, ModelMap map) throws SQLException {
		Member member = service.findMemberByPw(id, name, hp);
		if (member != null) {
			if (id.equals(member.getId())) {
				if (name.equals(member.getName())) {
					if (hp.equals(member.getHp())) {

						System.out.println("PW 찾기 성공");
						System.out.println(member.getId() + ", "
								+ member.getName() + "," + member.getHp() + ","
								+ member.getPassword() + ", "
								+ member.getEmail());
						map.addAttribute("member", member);

						String subject = "[TopGay]FYTL 비번 안내";// 제목
						String content = member.getPassword(); // 본문
						String receiveAddress = member.getEmail(); // 받는 사람 이메일
																	// 주소
						String receiveName = member.getName(); // 받는 사람 이름

						MimeMessage message = mailSender.createMimeMessage();

						try {
							// HTML O, 파일첨부 O, 파일 삽입 O
							MimeMessageHelper messageHelper = new MimeMessageHelper(
									message, true, "UTF-8");
							messageHelper.setSubject(subject);

							String htmlContent = "<p align=\"center\"><img src='cid:fytl' /></p>"
									+ "<p>"
									+ "안녕하세요. FYTL 의 탑게이입니다.</br>"
									+ "</p>"
									+ "<h3>요청하신 비밀번호 안내 입니다.</h3>"
									+ "<h4>요청 하신 비밀 번호는</h4>"
									+ "<p>"
									+ content
									+ "<h4>입니다.</h4>"
									+ "<br/>홈페이지에 접속하셔서 비밀번호를 반드시 변경하시기 바랍니다."
									+ "</p>";

							messageHelper.setText(htmlContent, true);
							messageHelper
									.setFrom("koreaken01@gmail.com", "탑게이");
							messageHelper.setTo(new InternetAddress(
									receiveAddress, receiveName, "UTF-8"));
							messageHelper
									.addInline(
											"fytl",
											new FileDataSource(
											// TODO 경로 확인
													"C:\\day\\apache-tomcat-6.0.41\\webapps\\TopGay\\image\\logomain_s.png"));

						} catch (Throwable e) {
							e.printStackTrace();
							return "redirect:/admin/error.jsp";
						}

						try {
							mailSender.send(message);
						} catch (MailException e) {
							e.printStackTrace();
						}

						// return
						// "redirect:/admin/cscenter/login/getContentBack.do?no="+cscenter.getCscenterNo()+"&page="+page;
						return "member/pw_search";
					}
				}
			}
		} else {
			map.addAttribute("error_message", "정보가 잘못되었습니다. 다시 한번 정확히 검색 해주세요.");
		}
		return "member/find_pw";
	}
}
